<?php
namespace app\lib;
/** 
* 自定义工具
*/
class Helper {
    
     /**
     * 生成16位全局唯一码
     * 单线程循环下，都会产生重复
     *
     * @return string
     */
    public static function uniID(): string{
        $order_sn = ''
            .chr(65 + intval(date('Y') - 2018))     // 年(1)
            .\dechex(date('m'))                     // 月(1)
            .date('d')                              // 日(2)
            .sprintf('%02s',dechex(\rand(0,255)))   // 00-ff随机数(2)
            .\substr(\microtime(),2,5)              // 毫秒(5)
            .\substr(time(),-5)                     // 秒(5)
        ;
        return $order_sn;
    }

    public static function array2map($array,$field,$del=false){
        $res = [];
        foreach ($array as $v) {
            if (! isset($v[$field])) {
                return false;
            }
            $res[$v[$field]] = $v;
            if($del) unset($res[$v[$field]][$field]);
        }
        return $res;
    }

    /**
     * 将一维数组分块
     *
     * @param array $list 数据源
     * @param int $block 分块数量
     * @return array
     */
    public static function goBlock(array $list, int $block=500): array
    {
        $count = count($list);
        $round = floor($count / $block);
        $mod = $count % $block;
        $res = [];
        for ($i=0; $i < $round ; $i++) { 
            $res[] = array_slice($list, $i* $block, $block);
        }
        if ($mod) {
            $res[] = array_slice($list, $i*$block, $count - $i*$block);
        }
        return $res;
    }

    /**
     * 字符串转map
     *
     * @param string $str 形如 key1:123,key2:value2 字符串转化为数组
     * @return array
     */
    public static function str2map(string $str) :array
    {
        $arr = explode(',', $str);
        $res = [];
        foreach ($arr as $one) {
            if (empty($one)) {
                continue;
            }
            [$k, $v] = explode(':', $one, 2);
            $res[$k] = $v;
        }
        return $res;
    }

    /**
     * 字符串校验码
     *
     * @param string $s 字符串
     * @param bool $upp 是否区分大小写
     * @return 
     */
    public static function strSumC(string $s, $upp = false)
    {
        if ($upp) {
            $m = "0123456789ABCDEFGHTIJKLMOPQRSTUVWXYZabcdefghtijklmopqrstuvwxyz";
        }else{
            $m = "0123456789abcdefghtijklmopqrstuvwxyz";
        }
        $sum = 0;
        for ($i=0; $i < strlen($s) ; $i++) { 
            $sum += ord($s[$i]); 
        }
        return $m[$sum % strlen($m)];
    }

}